<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>药品在线招投标系统 - 业务流程图</title>
    <script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', 'SimSun', sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #2563eb;
            margin-bottom: 30px;
        }
        .export-buttons {
            text-align: center;
            margin-bottom: 20px;
        }
        .export-btn {
            background: #2563eb;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin: 0 10px;
            transition: background 0.3s;
        }
        .export-btn:hover {
            background: #1e40af;
        }
        .export-btn:disabled {
            background: #94a3b8;
            cursor: not-allowed;
        }
        .status-message {
            text-align: center;
            margin: 10px 0;
            padding: 10px;
            border-radius: 6px;
            display: none;
        }
        .status-message.success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #10b981;
        }
        .status-message.error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #ef4444;
        }
        .status-message.info {
            background: #dbeafe;
            color: #1e40af;
            border: 1px solid #3b82f6;
        }
        #mermaid-container {
            background: white;
            padding: 20px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
        }
        .mermaid {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 600px;
            background: white;
        }
        .instructions {
            margin-top: 30px;
            padding: 20px;
            background: #f1f5f9;
            border-radius: 8px;
            border-left: 4px solid #2563eb;
        }
        .instructions h2 {
            color: #1e293b;
            margin-top: 0;
        }
        .instructions ul {
            color: #64748b;
            line-height: 1.8;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>药品在线招投标系统 - 业务流程图</h1>
        <div class="export-buttons">
            <button class="export-btn" id="exportPngBtn" onclick="exportAsPNG()">📥 导出为PNG图片</button>
            <button class="export-btn" id="exportSvgBtn" onclick="exportAsSVG()">📥 导出为SVG图片</button>
            <button class="export-btn" onclick="exportAsPNGManual()">📥 备用：导出PNG</button>
        </div>
        <div class="status-message" id="statusMessage"></div>
        <div id="mermaid-container">
        <div class="mermaid" id="flowchart">
flowchart TD
    Start([开始]) --> Login{用户登录}
    Login -->|未注册| Register[注册账号]
    Register --> RegisterRole{选择角色}
    RegisterRole -->|投标单位| RegisterBidder[注册为BIDDER<br/>填写公司信息]
    RegisterRole -->|招标单位| RegisterTenderer[注册为TENDERER<br/>填写公司信息]
    RegisterBidder --> Login
    RegisterTenderer --> Login
    Login -->|已注册| AuthCheck{验证身份}
    AuthCheck -->|成功| RoleCheck{用户角色}
    AuthCheck -->|失败| Login
    
    RoleCheck -->|BIDDER<br/>投标单位| BidderDashboard[投标单位首页]
    RoleCheck -->|TENDERER<br/>招标单位| TendererDashboard[招标单位首页]
    RoleCheck -->|ADMIN<br/>管理员| AdminDashboard[管理员首页]
    
    %% 投标单位流程
    BidderDashboard --> ViewTenders[浏览招标信息]
    ViewTenders --> SelectTender[选择招标项目]
    SelectTender --> ViewTenderDetail[查看招标详情]
    ViewTenderDetail --> SubmitBid{提交投标}
    SubmitBid -->|填写投标信息| BidForm[填写投标表单<br/>产品批号/生产日期<br/>有效期/总金额等]
    BidForm --> SaveBid[保存投标信息]
    SaveBid --> MyBids[查看我的投标]
    ViewTenderDetail --> PostMessage[发布留言]
    ViewTenders --> Messages[留言板]
    Messages --> PostMessage
    
    %% 招标单位流程
    TendererDashboard --> CreateTender[发布招标]
    CreateTender --> TenderForm[填写招标表单<br/>招标编号/药品名称<br/>制药单位/包装要求<br/>总量/截止日期/保证金]
    TenderForm --> SaveTender[保存招标信息]
    SaveTender --> ViewTenders
    TendererDashboard --> ViewMyTenders[查看我的招标]
    ViewMyTenders --> ViewTenderBids[查看项目投标列表]
    ViewTenderBids --> ReviewBids[审核投标信息]
    TendererDashboard --> EditTender[编辑招标信息]
    EditTender --> TenderForm
    
    %% 管理员流程
    AdminDashboard --> UserManagement[用户管理]
    UserManagement --> ViewUsers[查看用户列表]
    ViewUsers --> ChangeRole[调整用户角色]
    ChangeRole --> UpdateRole[更新角色]
    UpdateRole --> ViewUsers
    AdminDashboard --> MessageManagement[留言管理]
    MessageManagement --> DeleteMessage[删除留言]
    DeleteMessage --> Messages
    AdminDashboard --> ViewTenders
    AdminDashboard --> ViewAllBids[查看所有投标]
    
    %% 通用流程
    PostMessage --> SaveMessage[保存留言]
    SaveMessage --> Messages
    MyBids --> End1([结束])
    ReviewBids --> End2([结束])
    ViewAllBids --> End3([结束])
    
    style Start fill:#e1f5ff
    style Login fill:#ffe1f5
    style Register fill:#fff5e1
    style BidderDashboard fill:#e1ffe1
    style TendererDashboard fill:#ffe1e1
    style AdminDashboard fill:#e1e1ff
    style End1 fill:#e1f5ff
    style End2 fill:#e1f5ff
    style End3 fill:#e1f5ff
        </div>
        </div>
        <div class="instructions">
            <h2>使用说明</h2>
            <h3>导出图片方法（按推荐顺序）：</h3>
            <ol>
                <li><strong>SVG导出（推荐）：</strong>点击"📥 导出为SVG图片"按钮，SVG格式清晰且文件小</li>
                <li><strong>备用PNG导出：</strong>如果SVG不可用，点击"📥 备用：导出PNG"按钮</li>
                <li><strong>PNG导出：</strong>点击"📥 导出为PNG图片"按钮（需要html2canvas库支持）</li>
                <li><strong>手动保存：</strong>右键点击流程图区域，选择"图片另存为"或"检查元素"后找到SVG元素保存</li>
                <li><strong>打印为PDF：</strong>使用浏览器的打印功能（Ctrl+P），选择"另存为PDF"</li>
                <li><strong>截图工具：</strong>使用系统截图工具或浏览器扩展进行截图</li>
            </ol>
            <h3>流程图说明：</h3>
            <ul>
                <li><span style="background:#e1ffe1; padding:2px 6px;">绿色</span>：投标单位相关流程</li>
                <li><span style="background:#ffe1e1; padding:2px 6px;">红色</span>：招标单位相关流程</li>
                <li><span style="background:#e1e1ff; padding:2px 6px;">蓝色</span>：管理员相关流程</li>
                <li><span style="background:#ffe1f5; padding:2px 6px;">粉色</span>：登录/注册流程</li>
            </ul>
            <p><strong>提示：</strong>如果导出按钮不工作，请等待几秒钟让流程图完全加载，然后重试。也可以查看页面顶部的状态提示信息。</p>
        </div>
    </div>
    <script>
        let mermaidReady = false;
        let html2canvasReady = false;
        const statusMessage = document.getElementById('statusMessage');

        function showStatus(message, type = 'info') {
            statusMessage.textContent = message;
            statusMessage.className = 'status-message ' + type;
            statusMessage.style.display = 'block';
            setTimeout(() => {
                statusMessage.style.display = 'none';
            }, 5000);
        }

        // 检查库是否加载完成
        function checkLibraries() {
            html2canvasReady = typeof html2canvas !== 'undefined';
            if (!html2canvasReady) {
                console.warn('html2canvas未加载，将使用SVG导出作为备用方案');
            }
        }

        // 等待Mermaid渲染完成
        function waitForMermaid(callback) {
            const checkInterval = setInterval(() => {
                const svg = document.querySelector('.mermaid svg');
                if (svg && svg.children.length > 0) {
                    clearInterval(checkInterval);
                    mermaidReady = true;
                    if (callback) callback();
                }
            }, 100);

            // 超时保护
            setTimeout(() => {
                clearInterval(checkInterval);
                if (!mermaidReady) {
                    showStatus('流程图加载超时，请刷新页面重试', 'error');
                }
            }, 10000);
        }

        mermaid.initialize({ 
            startOnLoad: true,
            theme: 'default',
            themeVariables: {
                primaryColor: '#ffffff',
                primaryTextColor: '#1e293b',
                primaryBorderColor: '#2563eb',
                lineColor: '#64748b',
                secondaryColor: '#f1f5f9',
                tertiaryColor: '#e1f5ff'
            },
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            }
        });

        // 导出为PNG图片（使用html2canvas）
        async function exportAsPNG() {
            const btn = document.getElementById('exportPngBtn');
            btn.disabled = true;
            btn.textContent = '⏳ 正在导出...';

            try {
                // 检查库是否加载
                checkLibraries();
                if (!html2canvasReady) {
                    showStatus('html2canvas库未加载，请使用SVG导出或备用方案', 'error');
                    btn.disabled = false;
                    btn.textContent = '📥 导出为PNG图片';
                    return;
                }

                // 等待Mermaid渲染完成
                if (!mermaidReady) {
                    showStatus('等待流程图加载完成...', 'info');
                    await new Promise(resolve => waitForMermaid(resolve));
                    await new Promise(resolve => setTimeout(resolve, 500));
                }

                const container = document.getElementById('mermaid-container');
                if (!container) {
                    throw new Error('容器元素未找到');
                }

                showStatus('正在生成图片，请稍候...', 'info');

                const canvas = await html2canvas(container, {
                    backgroundColor: '#ffffff',
                    scale: 2,
                    logging: false,
                    useCORS: true,
                    allowTaint: true,
                    width: container.scrollWidth,
                    height: container.scrollHeight
                });
                
                const link = document.createElement('a');
                link.download = 'business_flowchart.png';
                link.href = canvas.toDataURL('image/png');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                showStatus('PNG图片已成功下载！', 'success');
            } catch (error) {
                console.error('导出PNG失败:', error);
                showStatus('PNG导出失败: ' + error.message + '。请尝试使用SVG导出或备用方案。', 'error');
            } finally {
                btn.disabled = false;
                btn.textContent = '📥 导出为PNG图片';
            }
        }

        // 导出为PNG（备用方案：通过SVG转换）
        async function exportAsPNGManual() {
            try {
                const svg = document.querySelector('.mermaid svg');
                if (!svg) {
                    showStatus('SVG元素未找到，请等待流程图加载完成', 'error');
                    return;
                }

                showStatus('正在通过SVG生成PNG，请稍候...', 'info');

                // 获取SVG数据
                const svgData = new XMLSerializer().serializeToString(svg);
                const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
                const svgUrl = URL.createObjectURL(svgBlob);

                // 创建图片元素
                const img = new Image();
                img.crossOrigin = 'anonymous';
                
                await new Promise((resolve, reject) => {
                    img.onload = resolve;
                    img.onerror = reject;
                    img.src = svgUrl;
                });

                // 创建canvas
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                canvas.width = img.width * 2;
                canvas.height = img.height * 2;
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                // 下载
                const link = document.createElement('a');
                link.download = 'business_flowchart.png';
                link.href = canvas.toDataURL('image/png');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                URL.revokeObjectURL(svgUrl);
                showStatus('PNG图片已成功下载（通过SVG转换）！', 'success');
            } catch (error) {
                console.error('备用PNG导出失败:', error);
                showStatus('导出失败: ' + error.message, 'error');
            }
        }

        // 导出为SVG
        async function exportAsSVG() {
            const btn = document.getElementById('exportSvgBtn');
            btn.disabled = true;
            btn.textContent = '⏳ 正在导出...';

            try {
                // 等待Mermaid渲染完成
                if (!mermaidReady) {
                    showStatus('等待流程图加载完成...', 'info');
                    await new Promise(resolve => waitForMermaid(resolve));
                    await new Promise(resolve => setTimeout(resolve, 500));
                }

                const svg = document.querySelector('.mermaid svg');
                if (!svg) {
                    throw new Error('SVG元素未找到，请等待流程图加载完成');
                }

                showStatus('正在生成SVG图片...', 'info');

                const svgData = new XMLSerializer().serializeToString(svg);
                
                // 添加XML声明和样式
                const svgWithStyle = '<?xml version="1.0" encoding="UTF-8"?>\n' + 
                    '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' +
                    svgData;
                
                const svgBlob = new Blob([svgWithStyle], { type: 'image/svg+xml;charset=utf-8' });
                const svgUrl = URL.createObjectURL(svgBlob);
                
                const link = document.createElement('a');
                link.download = 'business_flowchart.svg';
                link.href = svgUrl;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                URL.revokeObjectURL(svgUrl);
                showStatus('SVG图片已成功下载！', 'success');
            } catch (error) {
                console.error('导出SVG失败:', error);
                showStatus('SVG导出失败: ' + error.message, 'error');
            } finally {
                btn.disabled = false;
                btn.textContent = '📥 导出为SVG图片';
            }
        }

        // 页面加载完成后初始化
        window.addEventListener('load', function() {
            checkLibraries();
            waitForMermaid(() => {
                showStatus('流程图加载完成，可以开始导出了！', 'success');
            });
        });

        // 延迟检查，确保所有库都已加载
        setTimeout(() => {
            checkLibraries();
            if (typeof html2canvas === 'undefined') {
                showStatus('提示：html2canvas库加载失败，建议使用SVG导出或备用PNG导出', 'info');
            }
        }, 2000);
    </script>
</body>
</html>

